package cn.echo.ecc.mq.consumer;

import static cn.echo.ecc.constants.MQConstants.*;
import cn.echo.ecc.constants.MQConstants;
import cn.echo.ecc.domain.MessageSms;
import cn.echo.ecc.dto.CourseOnlineSendMessageDto;
import cn.echo.ecc.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-sms",
        topic = COURSE_SMS_TOPIC,
        selectorExpression = COURSE_SMS_TAG,
        messageModel = MessageModel.CLUSTERING
)
public class CourseSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        // 1.防御性编程
        if (null == body) {
            return;
        }
        // 2.将字节数组转换为想要的对象CourseOnlineSendMessageDto
        String param = new String(body, StandardCharsets.UTF_8);
        CourseOnlineSendMessageDto courseOnlineSendMessageDto = JSON.parseObject(param, CourseOnlineSendMessageDto.class);
        // 3.发送短信
        log.info("发送短信成功！");
        // 4.保存短信日志
        saveMessageSms(courseOnlineSendMessageDto);
    }

    /**
     * 保存短信日志
     * @param courseOnlineSendMessageDto
     */
    private void saveMessageSms(CourseOnlineSendMessageDto courseOnlineSendMessageDto) {
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(courseOnlineSendMessageDto.getTitle());
        messageSms.setContent(courseOnlineSendMessageDto.getContent());
        messageSms.setSendTime(new Date());
        courseOnlineSendMessageDto.getUserOnlineSendMessageDtos().forEach(e -> {
            messageSms.setUserId(e.getUserId());
            messageSms.setPhone(e.getContact());
            messageSmsService.insert(messageSms);
        });
    }
}
